// 消息类型配置
const MESSAGE_TYPES = {
    success: {
        icon: 'check-circle',
        title: '成功'
    },
    warning: {
        icon: 'exclamation-triangle',
        title: '警告'
    },
    error: {
        icon: 'x-circle',
        title: '错误'
    },
    info: {
        icon: 'info-circle',
        title: '信息'
    }
};

// 默认配置
const DEFAULT_OPTIONS = {
    type: 'info',
    title: '',
    message: '',
    duration: 5000,
    showProgress: true,
    closable: true,
    position: 'top-right'
};

export function initializeMessageToast(shadowRoot, component) {
    const container = shadowRoot.querySelector('.message-toast-container');
    const toast = shadowRoot.querySelector('#messageToast');
    const icon = shadowRoot.querySelector('#toastIcon sl-icon');
    const title = shadowRoot.querySelector('#toastTitle');
    const message = shadowRoot.querySelector('#toastMessage');
    const closeBtn = shadowRoot.querySelector('#toastClose');

    let currentTimeout = null;
    let progressTimeout = null;

    // 关闭按钮事件
    closeBtn.addEventListener('click', () => {
        component.hide();
    });

    // 显示消息
    component.show = function(options = {}) {
        const config = { ...DEFAULT_OPTIONS, ...options };
        const typeConfig = MESSAGE_TYPES[config.type] || MESSAGE_TYPES.info;

        // 清除之前的定时器
        if (currentTimeout) {
            clearTimeout(currentTimeout);
            currentTimeout = null;
        }
        if (progressTimeout) {
            clearTimeout(progressTimeout);
            progressTimeout = null;
        }

        // 设置内容
        icon.setAttribute('name', typeConfig.icon);
        title.textContent = config.title || typeConfig.title;
        message.textContent = config.message;

        // 设置样式类型
        toast.className = 'message-toast';
        toast.classList.add(config.type);

        // 设置进度条
        if (config.showProgress && config.duration > 0) {
            toast.classList.add('with-progress');
            toast.style.setProperty('--progress-duration', `${config.duration}ms`);
            
            // 延迟添加进度条动画，确保样式已应用
            setTimeout(() => {
                toast.style.setProperty('transition', `transform 0.3s cubic-bezier(0.4, 0, 0.2, 1)`);
                toast.querySelector('::after')?.style.setProperty('transition', `transform ${config.duration}ms linear`);
            }, 50);
        }

        // 设置关闭按钮可见性
        closeBtn.style.display = config.closable ? 'flex' : 'none';

        // 显示动画
        container.style.display = 'block';
        setTimeout(() => {
            toast.classList.add('show');
        }, 10);

        // 自动关闭
        if (config.duration > 0) {
            currentTimeout = setTimeout(() => {
                component.hide();
            }, config.duration);
        }

        return component;
    };

    // 隐藏消息
    component.hide = function() {
        if (currentTimeout) {
            clearTimeout(currentTimeout);
            currentTimeout = null;
        }
        if (progressTimeout) {
            clearTimeout(progressTimeout);
            progressTimeout = null;
        }

        toast.classList.remove('show');
        toast.classList.add('hide');

        setTimeout(() => {
            container.style.display = 'none';
            toast.classList.remove('hide', 'with-progress');
            toast.className = 'message-toast';
            
            // 触发隐藏事件
            component.dispatchEvent(new CustomEvent('toast-hidden'));
        }, 300);

        return component;
    };

    // 快捷方法
    component.success = function(message, options = {}) {
        return component.show({ ...options, type: 'success', message });
    };

    component.warning = function(message, options = {}) {
        return component.show({ ...options, type: 'warning', message });
    };

    component.error = function(message, options = {}) {
        return component.show({ ...options, type: 'error', message });
    };

    component.info = function(message, options = {}) {
        return component.show({ ...options, type: 'info', message });
    };

    // 初始状态
    container.style.display = 'none';
}

// 全局消息提示工具类
export class MessageToastManager {
    constructor() {
        this.toasts = new Map();
        this.container = null;
        this.init();
    }

    init() {
        // 创建全局容器
        this.container = document.createElement('div');
        this.container.className = 'global-toast-container';
        this.container.style.cssText = `
            position: fixed;
            top: 20px;
            right: 20px;
            z-index: 10000;
            pointer-events: none;
            display: flex;
            flex-direction: column;
            gap: 10px;
        `;
        document.body.appendChild(this.container);
    }

    show(options = {}) {
        const config = { ...DEFAULT_OPTIONS, ...options };
        const id = Date.now() + Math.random();

        // 创建消息元素
        const toastElement = document.createElement('message-toast');
        toastElement.setAttribute('data-id', id);
        
        this.container.appendChild(toastElement);

        // 等待组件初始化后显示消息
        setTimeout(() => {
            if (toastElement.show) {
                toastElement.show(config);
            }
        }, 100);

        // 监听隐藏事件
        toastElement.addEventListener('toast-hidden', () => {
            this.remove(id);
        });

        this.toasts.set(id, toastElement);
        return id;
    }

    remove(id) {
        const toast = this.toasts.get(id);
        if (toast && toast.parentNode) {
            toast.parentNode.removeChild(toast);
            this.toasts.delete(id);
        }
    }

    success(message, options = {}) {
        return this.show({ ...options, type: 'success', message });
    }

    warning(message, options = {}) {
        return this.show({ ...options, type: 'warning', message });
    }

    error(message, options = {}) {
        return this.show({ ...options, type: 'error', message });
    }

    info(message, options = {}) {
        return this.show({ ...options, type: 'info', message });
    }

    clear() {
        this.toasts.forEach((toast, id) => {
            this.remove(id);
        });
    }
}

// 创建全局实例
export const messageToast = new MessageToastManager();